from django.core import serializers
from django.utils.encoding import iri_to_uri
from mongoengine import *
from models import StringToLatLong
import urllib, math, json

MQKEY = r'Fmjtd%7Cluu7n16a2d%2C80%3Do5-5rag1'

def locations_to_ll(locations):
	locations = list(locations)
	numLists = int(math.ceil(len(locations)/float(100)))
	coords = []
	
	for i in range(numLists):
		content = r'http://www.mapquestapi.com/geocoding/v1/batch?key=%s&callback=renderBatch' % MQKEY
		for location in locations[i*100:100]:
			if not location is None and location.strip()!='':
				content += '&location=%s' % iri_to_uri(location)
		content += '&thumbmaps=false&maxResults=1&outFormat=file'
		#print content
	
		json_text = urllib.urlopen(content).readlines()[0]
		#print json_text
		try:
			json_obj = json.loads(json_text)
		except:
			print 'locations_to_ll couldn\'t load the json object'
			print json_text
			return
		#print json.dumps(json_obj, sort_keys=True, indent=4), '\n\n'
		#json = simplejson.loads(content)
		#print json_obj, '\n\n'
	
		for location in json_obj['results']:
			if not location['locations']:
				continue
			resultsDict = location['locations'][0]
			if(resultsDict['adminArea3']!=''): # seems to be the only way to make sure that it's a real result
				latLng = resultsDict['latLng']
				state = resultsDict['adminArea3']
				#print latLng
				#coords.append( (latLng['lat'],latLng['lng']) )
				coord = StringToLatLong(string = location['providedLocation']['location'], latLong=[latLng['lat'],latLng['lng']], state=state)
				coord.save()
				# print 'saving %s as (%f,%f)' % (coord.string, coord.latLong[0], coord.latLong[1])

def ll_to_state(ll):
	#URL = r'http://www.mapquestapi.com/geocoding/v1/reverse?key=%s&lat=%s&lng=%s&callback=renderReverse&outFormat=file' % (MQKEY, ll[0], ll[1])
	URL = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s,%s&sensor=false' % (ll[0], ll[1])
	# print URL
	json_obj = json.loads(urllib.urlopen(URL).read())
	#return json_obj['results'][0]['locations'][0].get('adminArea3',None)
	if json_obj['status'] != 'OK':
		print 'll_to_state not OK'
		return None
	
	for component in json_obj['results'][0]['address_components']:
		if component['short_name'] in states():
			return component['short_name']
			
	return None

def states():
	return ['AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA',
	'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NK', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA',
	'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']
